package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
/**
 * 数据库操作类
 */
public class DbcpConnectionPool {
	
	public DbcpConnectionPool(){
	}
	/**
	 * 获取数据库连接
	 * @return Connection对象
	 * @throws SQLException
	 */
	static String driver="com.mysql.cj.jdbc.Driver";
	static String url="jdbc:mysql://localhost:3306/wsdc?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai";
	static String user="root";
	static String password="root";
	protected static Statement s = null;
	protected static ResultSet rs = null;
	protected static Connection conn = null;
	//从连接池中获取连接
	public static synchronized Connection getConnection() throws SQLException{
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, password);
		}catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		return conn;
	}
	/**
	 * 执行select语句
	 * @param sql 要执行的sql语句
	 * @return 结果集
	 */
	public static ResultSet runSelect(String sql){
		ResultSet rs = null;
		try {
			Statement stat = conn.createStatement();
			rs = stat.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
	/**
	 * 执行增删改sql语句
	 * @param sql 要执行的sql语句
	 * @return 改变的记录数
	 */
	public static int runSql(String sql){
		int i = 0;
		try {
			Statement stat = conn.createStatement();
			i = stat.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return i;
	}
}
